package cn.czh0123.service.impl;

import cn.czh0123.domain.User;
import cn.czh0123.exception.BusinessException;
import cn.czh0123.mapper.UserMapper;
import cn.czh0123.msg.UserCodeMsg;
import cn.czh0123.service.IUserService;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
* 用户服务接口实现
*/
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService  {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        User findUser = userMapper.selectOne(wrapper);
        if (findUser == null) {
            throw new BusinessException(UserCodeMsg.LOGIN_ERROR);
        }
        if (!findUser.getPasswordHash().equals(DigestUtils.md5DigestAsHex(user.getPasswordHash().getBytes()))) {
            throw new BusinessException(UserCodeMsg.LOGIN_ERROR);
        }
        findUser.setLastLoginTime(new Date());
        userMapper.updateById(findUser);
        doLogin(findUser);
        return findUser;
    }

    @Override
    public User register(User user) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        User findUser = userMapper.selectOne(wrapper);
        if (findUser != null) {
            throw new BusinessException(UserCodeMsg.USERNAME_EXIST);
        }
        user.setPasswordHash(DigestUtils.md5DigestAsHex(user.getPasswordHash().getBytes()));
        user.setRegistrationDate(new Date());
        user.setLastLoginTime(new Date());
        user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
        userMapper.insert(user);

        doLogin(user);
        return user;
    }

    private void doLogin(User user) {
        StpUtil.login(user.getId());
        StpUtil.getSession().set("user", user);
        log.info("用户{}登录成功", user.getUsername());

        // TODO 后续可以设置权限，暂时不做

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        user.setSaToken(tokenInfo.getTokenValue());
    }
}
